import { _decorator, Component, EventMouse, EventTouch, find, Input, input, instantiate, Label, Node, tween, UITransform, Vec2, Vec3 } from 'cc';
import { card_base } from './card_base';
import { plant_base } from './plant_base';
import { sun } from './sun';
const { ccclass, property } = _decorator;

@ccclass('MouseManager')
export class MouseManager extends Component {

    private plantPrefabNode: Node = null;
    @property(Node)
    private totalPointNode: Node = null;
    @property
    totalPoint: number = 0;

    public static getInstance(): MouseManager {
        return this._instance;
    }
    private static _instance: MouseManager = null;

    protected onLoad(): void {
        if(MouseManager._instance === null)
        {
            MouseManager._instance = this;
        }
        input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
        input.on(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
        //初始化阳光总数
        this.totalPointNode.getComponent(Label).string = this.totalPoint.toString();
    }

    protected onDestroy(): void {
        MouseManager._instance = null;
        //移除所有事件监听
        input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
        input.off(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
        input.off(Input.EventType.MOUSE_UP, this.onMouseUp, this);
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.off(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    /**
     * @param path 父母节点路径
     * @param worldPos 世界坐标
     * @returns 找到的节点或null
     * 该方法用于在指定路径下查找包含指定世界坐标的节点
     */
    findNodeByPath(path: string, worldPos: Vec3): Node
    {
        const parentNode = find(path);
        if(!parentNode)
        {
            console.error('未找到节点，请检查路径：', path);
            return null;
        }
        console.log('parentNode.lenth:',  parentNode.children.length, parentNode.name);
        for(let i = 0; i < parentNode.children.length; i++)
        {
            const childNode = parentNode.children[i];
            if(!childNode)
            {
                console.error('节点不存在:', childNode.name);
                continue;
            }
            console.log('childNode name:', childNode.name);
            const uiTrans = childNode.getComponent(UITransform);
            if(!uiTrans)
            {
                console.error('节点缺少UITransform组件：',childNode.name);
                continue;
            }
            if(uiTrans.getBoundingBoxToWorld().contains(new Vec2(worldPos.x, worldPos.y)))
            {
                console.log('找到节点：', childNode.name);
                return childNode;
            }
        }
        return null;
    }

    onMouseDown(event: EventMouse)
    {
        console.log("Mouse Down at: ", event.getLocation());
        let worldPos = new Vec3(event.getLocationX(), event.getLocationY(), 0);
        //处理卡片点击
        let pressNode = this.findNodeByPath('Canvas/chooseList/ChooserBackground', worldPos);
        console.log('Pressed Node: ', pressNode? pressNode.name: 'null');
        if(pressNode)
        {
            let cardBase = pressNode.getComponent(card_base);
            if(!cardBase || !cardBase.isEnable() || cardBase.getNeedPoint() > this.totalPoint)
            {
                console.log('Card is not enable or missing card_base component or needPoint > totalPoint:'
                    , pressNode.name);
                return;
            }

            console.log("Pressed Node: ", pressNode.name);
            let uiTrans = pressNode.getComponent(UITransform);
            if(!uiTrans)
            {
                console.error(' onMouseDown: 节点缺少UITransform组件：', pressNode.name);
                return;
            }
            
            let localPos = uiTrans.convertToNodeSpaceAR(worldPos);
            this.plantPrefabNode = instantiate(cardBase.getCurrentPrefab());
            this.plantPrefabNode.setParent(pressNode);
            return;
        }
    }

    onMouseUp(event: EventMouse)
    {
        if(this.plantPrefabNode)
        {
            let worldPos = new Vec3(event.getLocationX(), event.getLocationY(), 0);
            let cellNode = this.findNodeByPath('Canvas/cellList', worldPos);
            if(!cellNode)
            {
                console.log('未找到cell节点');
                this.plantPrefabNode.destroy();
                this.plantPrefabNode = null;
                return;
            }
            cellNode.addChild(this.plantPrefabNode);
            let localPos = cellNode.getComponent(UITransform).convertToNodeSpaceAR(cellNode.getWorldPosition());
            this.plantPrefabNode.setPosition(localPos);
             this.plantPrefabNode.getComponent(plant_base).startGrow();
            this.plantPrefabNode = null;
            return;
        }
        let selNode = this.findNodeByPath('Canvas/sunList', new Vec3(event.getLocationX(), event.getLocationY(), 0));
        if(selNode)
        {
            let endWorldPos = this.totalPointNode.getWorldPosition();
            const labLocalPos = find('Canvas/sunList').getComponent(UITransform).convertToNodeSpaceAR(endWorldPos);
            tween(selNode).to(1, { position: new Vec3(labLocalPos.x, labLocalPos.y, labLocalPos.z) }
                , { 'easing': 'smooth' })
                .call(() => {
                    //增加阳光点数，删除node节点
                    selNode.destroy();
                    this.addPoint(selNode.getComponent(sun).getSunPoint());
                }).start();
        }
        
    }

    sunMouseMove(event: EventMouse)
    {
        this.onMouseMove(event);
    }

    onMouseMove(event: EventMouse)
    {
        if (this.plantPrefabNode) {
            let worldPos = new Vec3(event.getLocationX(), event.getLocationY(), 0);
            //let localPos = this.plantPrefabNode.getComponent(UITransform).convertToNodeSpaceAR(worldPos);
            this.plantPrefabNode.setWorldPosition(worldPos);
            return;
        }
        
    }

    onTouchStart(event: EventTouch)
    {
        
    }

    onTouchMove(event: EventTouch)
    {

    }

    onTouchEnd(event: EventTouch)
    {

    }

    onTouchCancel(event: EventTouch)
    {

    }

    public getTotalPoint(): number
    {
        return this.totalPoint;
    }

    public getMoveEndPostion(): Vec3
    {
        if(!this.totalPointNode)
        {
            return new Vec3(0, 0, 0);
        }
        return this.totalPointNode.getWorldPosition();
    }

    public addPoint(point: number): void
    {
        this.totalPoint += (point);
        if(this.totalPointNode)
        {
            this.totalPointNode.getComponent(Label).string = this.totalPoint.toString();
        }
    }

}


